package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    /**
     * 新增地址
     * @param addressBook
     */
    public void save(AddressBook addressBook) {
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询地址簿
     * @return
     */
    public List<AddressBook> list() {
        Long currentId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder()
                .userId(currentId)
                .build();
        return addressBookMapper.list(addressBook);
    }

    /**
     * 查询默认地址
     * @return
     */
    public AddressBook getDefault() {
        Long currentId = BaseContext.getCurrentId();
        return addressBookMapper.getDefault(currentId);
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    public void setDefault(AddressBook addressBook) {
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        // 需要将该用户下所有的默认地址都设置为非默认
        List<AddressBook> list = addressBookMapper.list(addressBook);
        list.forEach(item ->{
            if(item.getIsDefault() == 1){
                item.setIsDefault(0);
                addressBookMapper.setNotDefault(item.getId());
            }
        });
        addressBookMapper.setDefault(addressBook.getId());
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    public AddressBook getById(Long id) {
        Long currentId = BaseContext.getCurrentId();
        AddressBook addressBook  = AddressBook.builder()
                .id(id)
                .userId(currentId)
                .build();
        return addressBookMapper.getById(addressBook);
    }

    /**
     * 修改地址
     * @param addressBook
     */
    public void update(AddressBook addressBook) {
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        AddressBook a = addressBookMapper.getById(addressBook);
        addressBook.setIsDefault(a.getIsDefault());
        addressBookMapper.update(addressBook);
    }

    /**
     * 删除地址
     * @param id
     */
    public void delete(Long id) {
        AddressBook addressBook = AddressBook.builder()
               .id(id)
                .userId(BaseContext.getCurrentId())
               .build();
        addressBookMapper.delete(addressBook);
    }
}
